<template>
  <div class="app-container">
    <el-row type="flex" class="row-bg" justify="center" :gutter="20">
      <el-col :span="12">
            <el-select v-model="param.userType" placeholder="请选择用户类型" >
              <el-option label="学生" value="2"></el-option>
              <el-option label="教师" value="1"></el-option>
              <el-option label="管理员" value="0"></el-option>
            </el-select>
      <el-input
      placeholder="请输入姓名"
      prefix-icon="el-icon-search" clearable v-model="param.searchName">
      </el-input>
      </el-col>
      <el-col :span="4">
    <el-button icon="el-icon-search" circle @click="selectUser"></el-button>
      </el-col>
    </el-row>
    <el-row>
       <el-button type="primary" @click="dialogFormVisible = true">导入人员</el-button>
       <el-dialog title="导入人员" :visible.sync="dialogFormVisible">
            <el-radio v-model="radio" label="1">导入学生</el-radio>
            <el-radio v-model="radio" label="2">导入教师</el-radio>
            <el-upload
              class="upload-demo"
              limit = 1
              drag
              :action="actionUrl"
              :on-success="onSuccess"
              :on-error="onError"
              :on-remove="onRemove"
              :on-exceed="onExceed"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过5M</div>
            </el-upload>
            <div v-if="radio === '1' "><a :href="downloadUrl+'/upload/导入学生模板_实习实训管理系统.xlsx'" download="导入学生模板_实习实训管理系统.xlsx">下载导入学生模板</a></div>
            <div v-if="radio === '2'"><a :href="downloadUrl+'/upload/导入教师模板_实习实训管理系统.xlsx'" download="导入教师模板_实习实训管理系统.xlsx">下载导入教师模板</a></div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitFile">确 定</el-button>
          </div>
        </el-dialog>
        <el-button type="primary" @click="addVisible = true" style="float:right;">新增人员</el-button>
       <el-dialog title="新增人员" :visible.sync="addVisible">
            <el-form ref="form" :model="addUserParams" label-width="80px">
              <el-form-item label="姓名">
                <el-input v-model="addUserParams.name"></el-input>
              </el-form-item>
              <el-form-item label="用户类型">
                <el-select v-model="addUserParams.userType" placeholder="请选择用户类型">
                  <el-option label="学生" value="2"></el-option>
                  <el-option label="教师" value="1"></el-option>
                  <el-option label="管理员" value="0"></el-option>
                </el-select>
              </el-form-item>
              <div v-if="addUserParams.userType === '1'||addUserParams.userType === '0'">
                  <el-form-item label="工号">
                    <el-input v-model="addUserParams.jobNumber"></el-input>
                  </el-form-item>
                  <el-form-item  label="性别">
                    <template>
                      <el-radio v-model="addUserParams.teachGender" label="0">男</el-radio>
                      <el-radio v-model="addUserParams.teachGender" label="1">女</el-radio>
                    </template>
                  </el-form-item>
                  <el-form-item label="手机号码">
                    <el-input v-model="addUserParams.teachPhone"></el-input>
                  </el-form-item>
                </div>
                <div v-if="addUserParams.userType === '2' ">
                  <el-form-item label="学号">
                    <el-input v-model="addUserParams.studentNumber"></el-input>
                  </el-form-item>
                  <el-form-item label="性别">
                    <template>
                      <el-radio v-model="addUserParams.studentGender" label="0">男</el-radio>
                      <el-radio v-model="addUserParams.studentGender" label="1">女</el-radio>
                    </template>
                  </el-form-item>
                  <el-form-item label="学院">
                    <el-input v-model="addUserParams.college"></el-input>
                  </el-form-item>
                  <el-form-item label="年级">
                    <el-input v-model="addUserParams.grade"></el-input>
                  </el-form-item>
                  <el-form-item label="班级">
                    <el-input v-model="addUserParams.class"></el-input>
                  </el-form-item>
                  <el-form-item label="手机号码">
                    <el-input v-model="addUserParams.studentPhone"></el-input>
                  </el-form-item>
                </div>
            </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">立即创建</el-button>
          </div>
        </el-dialog>
    <el-table :data="userList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="账号" width="200">
        <template slot-scope="scope">
          {{ scope.row.userAccount }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" width="220">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="手机号">
        <template slot-scope="scope">
          {{ scope.row.userPhone }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="用户类型">
        <template slot-scope="scope">
          {{ scope.row.userType }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleAssignRole(scope)">分配用户角色</el-button>
          <el-popconfirm
            @onConfirm ="deleteUser(scope)"
            title="确定删除吗？"
          >
           <el-button slot="reference" type="primary" size="small" >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
      
    </el-table>
    </el-row>
    <!--分页组件-->
<el-pagination background layout="prev, pager, next"  prev-text="上一页"
        next-text="下一页"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currpage"
        :page-size="pageSize"
        :total="total"></el-pagination>
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle">
      角色列表<br/><br/>
      <el-checkbox-group v-model="checkedList">
        <el-checkbox v-for="(role, index) in roleList" :key="index" :label="role.roleName"></el-checkbox>
      </el-checkbox-group>
      <br/>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getUserList, assignUserRoles,importTeach,importStudent,addUser,deleteUser} from '@/api/user'
import { deepClone } from '@/utils'
import { selectRoleList } from '@/api/role'
import checkPermission from '@/utils/permission' // 权限判断函数
import { searchUser } from '@/api/remote-search'

const defaultUser = {
  userId: 0,
  userAccount:'',
  userName: '',
  userPhone:'',
  sex:'',
  roleList:[],
  userType:''
}

export default {
  data() {
    return {
      downloadUrl:process.env.VUE_APP_BASE_API,
      actionUrl:process.env.VUE_APP_BASE_UPLOAD,
      user: Object.assign({}, defaultUser),
      userList: [],
      dialogVisible: false,
      addVisible:false,
      dialogTitle: '',
      roleList: [],
      checkedList: [],
      param :{
      start: 0,
      limit: 10,
      searchName:'',
      userType:'2'
      },
      pageSize: 10, //每一页的数据大小
      currpage: 1, //当前页
      total:0,//总条数
      dialogFormVisible: false,
      radio: '1',
      addRadio:'1',
      inportParams:{
        filePath:''
      },
      addUserParams:{
          name: '',
          userType: '2',
          studentNumber:'',
          studentGender:'0',
          college:'', 
          grade:'',
          class:'',
          studentPhone:'',
          jobNumber:'',
          teachPhone:'',
          teachGender:'0'
      },
      deleParams:{
        userId:''
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  //页面打开时执行的方法
  created() {
    this.getUserList()
    this.getRoleList()
  },
  methods: {
    checkPermission, 
    async getUserList() {
      let res = await getUserList(this.param)
      this.userList = res.beans
      this.total = res.bean.total
    },
    async getRoleList() {
      let res = await selectRoleList(this.param)
      this.roleList = res.beans
    },
    handleAssignRole(scope) {
      this.user = deepClone(scope.row)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dialogTitle = '给 ' + scope.row.userName + ' 分配角色'
      this.$nextTick(() => {
        this.checkedList.splice(0, this.checkedList.length)
        let roles = scope.row.roleList
        roles.forEach( role => {
          this.checkedList.push(role.roleName)
        })
        console.log(this.checkedList)
      })
    },
    async confirmUser() {
      this.user.roleList.splice(0, this.user.roleList.length)
      this.checkedList.forEach( roleName => {
        this.roleList.forEach( role => {
          if(roleName === role.roleName) {
            this.user.roleList.push(role)
            return
          }
        })
      })

      await assignUserRoles(this.user)
      this.getUserList()
      this.dialogVisible = false
    },
    //页大小变化
     handleSizeChange(val) {
      this.pageSize = val;
      this.param.start = this.pageSize*(this.currpage-1)
      this.getUserList();
    },
    //页标号变化
    handleCurrentChange(val) {
      this.currpage = val;
      this.param.start = this.pageSize*(this.currpage-1)
      this.getUserList();
    },
    selectUser(){
      this.param.start = 0;
      this.param.limit = 10;
      this.currpage = 1;
      this.getUserList()
    },
    //文件上传成功时
    onSuccess(response, file, fileList){
      this.inportParams.filePath = response.bean.url
    },
    //文件上传失败时执行
    onError(err, file, fileList){
      console.log(err)
    },
    //移除文件时执行
    onRemove(file, fileList){
      this.inportParams.filePath = '';
    },
    //文件超限时执行
    onExceed(files, fileList){
      this.$message({
              type: 'warning',
              message: '一次只能上传一个文件哦！'
            })
    },
    submitFile(){
      if(this.radio === '1'){
        this.importStudent();
      }else if(this.radio === '2'){
        this.importTeach();
      }
      this.dialogFormVisible = false
    },
    async importTeach(){
      await importTeach(this.inportParams).then(()=>{
            this.$message({
              type: 'success',
              message: '导入任务执行成功!请稍后在消息中心查看执行结果！'
            })}
          ).catch(err=>{
            this.$message({
              type: 'error',
              message: '导入失败!'
            })
        })
    },
    async importStudent(){
      await importStudent(this.inportParams).then(()=>{
            this.$message({
              type: 'success',
              message: '导入任务执行成功!请稍后在消息中心查看执行结果！'
            })}
          ).catch(err=>{
            this.$message({
              type: 'error',
              message: '导入失败!'
            })
        })
    },
    addUser(){
      addUser(this.addUserParams).then(()=>{
            this.$message({
              type: 'success',
              message: '新增成功!'
              
            })
            this.addVisible = false
            this.getUserList()
            //清空已保存属性值
            Object.keys(this.addUserParams).forEach(key => (this.addUserParams[key] = ''))
            }
          ).catch(err=>{
            this.$message({
              type: 'error',
              message: '新增失败!'
            })
        })
    },
    deleteUser(scope){
      this.deleParams.userId  = scope.row.userId,
      deleteUser(this.deleParams).then(()=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
              
            })
            this.addVisible = false
            this.getUserList()
            }
          ).catch(err=>{
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
